package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.entity.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <b><code>LoginCheckFilter</code></b>
 * <p/>
 * 检查用户是否已经登录的过滤器
 * <p/>
 * <b>Creation Time:</b> 16/06/2024 21:43.
 *
 * @author yanjr
 * @since reggie_take_out
 */
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    // 路径匹配器，支持通配符
    public static final AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        // 获取本次请求URI
        String uri = request.getRequestURI();
        // 本次请求是否需要处理
        // 定义不需要处理的请求路径
        String[] uris = new String[]{"/employee/login", "/employee/logout", "/user/login", "/user/logout", "/backend/**", "/front/**"};
        // 不处理直接放行
        // 判断登录状态，如果已登录，则直接放行
        if (check(uri, uris) || request.getSession().getAttribute("employee") != null) {
            Long userId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentUser(userId);
            filterChain.doFilter(request, response);
            return;
        }
        // 如果没有登录则返回未登录结果，通过输出流的方式向客户端页面响应数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }

    /**
     * 路径匹配
     * @param uri 请求路径
     * @param uris  放行路径
     * @return 是否放行
     */
    public boolean check(String uri, String[] uris) {
        for (String s : uris) {
            if (antPathMatcher.match(s, uri)) {
                return true;
            }
        }
        return false;
    }
}
